package org.nanotek.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.TypedQuery;

import org.json.JSONArray;
import org.nanotek.Base;
import org.nanotek.beans.ArtistCredit;
import org.nanotek.beans.Release;
import org.nanotek.dao.ReleaseDAO;

@Stateless
@SuppressWarnings("serial")
@TransactionManagement(TransactionManagementType.CONTAINER)
public class ReleaseDAOImpl extends LocalBaseDAO<Release> implements ReleaseDAO {

	@Override
	public  List<Release> findReleases(List<Base<?>> artistCredits) {
		String jpql = "Select r from Release r inner join r.artistCreditReference a where a.artistCreditId in (:param)";
		TypedQuery<Release>  query = em.createQuery(jpql,Release.class);
		/*long [] values = artistCredits.stream().map(p -> p.getId()).toArray();*/
		List<Long>credits = new ArrayList<Long>();
		for (Base<?> a : artistCredits){
			ArtistCredit credit = (ArtistCredit) a;
			credits.add((Long) credit.getArtistCreditId());
		}
		query.setParameter("param",credits);
		return query.getResultList();
	}

	@Override
	public  List<Release> findReleases(String artistCredits) {
		
		JSONArray array = new JSONArray(artistCredits);
		List<String> values = new ArrayList<String>();
		for (int i = 0 ; i < array.length();i++)
		{ 
			String id = array.getString(i);
			values.add(id);
		}
		
		String jpql = "Select r from Release r inner join r.artistCreditReference a where a.artistCreditId in (:param)";
		return em.createQuery(jpql,Release.class).setParameter("param", values).getResultList();
	}
	
	@Override
	public List<Release> loadAll() {
		return em.createQuery("from Release",Release.class).getResultList();
	}

	@Override
	public List<Release> listRecords(Integer firstResult, Integer maxResults) {
		return  em.createQuery("from Release",Release.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
	}

}
